<template>
  <div class="container">
    <div ref="searchRef">
      <el-form :inline="true" :model="formInline" class="grids gridColumns5">
        <el-form-item label="授课方向">
          <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" v-model="formInline.teachingDirection" default-first-option placeholder="请选择" clearable>
            <el-option v-for="(item,index) in teachingDirectionOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课类型">
          <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" v-model="formInline.teachingType" placeholder="请选择" clearable>
            <el-option v-for="(item,index) in teachingTypeOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课项目">
          <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" v-model="formInline.teachingProgram" placeholder="请选择" clearable>
            <el-option v-for="(item,index) in teachingProgramOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="课时">
          <el-input v-model="formInline.classHour" placeholder="课时" clearable />
        </el-form-item>
        <el-form-item label="讲师姓名">
          <el-input v-model="formInline.lecturerName" placeholder="讲师姓名" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="formInline.mobile" placeholder="联系电话" clearable />
        </el-form-item>
        <el-form-item label="课酬(天)">
          <el-input v-model="formInline.lessonRemuneration" placeholder="课酬（天）" type="number" clearable />
        </el-form-item>
        <el-form-item label="常住地">
          <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" v-model="formInline.permanentResidence" placeholder="请选择" clearable>
            <el-option v-for="(item,index) in permanentResidenceOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="init">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="actionBtn">
        <el-button type="primary" @click="drawer=true">新增讲师</el-button>
        <el-button type="primary" plain @click="importTemplate">导入</el-button>
        <!-- <el-button type="primary" plain @click="handleExport(1)">excel模板导出</el-button> -->
        <el-button @click="exportExcel">导出</el-button>
        <el-button @click="handelDelete" type="danger" :disabled="!selectData.length">删除</el-button>
      </div>
    </div>

    <input type="file" @change="handleFileUpload" v-show="false" ref="inputFile" />

    <el-table :data="tableData.rows" :max-height="tableHeight" @selection-change="handleSelectionChange" v-loading="loading">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column type="index" width="50" fixed="left" />
      <el-table-column prop="teachingDirection" label="授课方向" fixed="left" width="100">
        <template #default="scope">
          <div class="button">{{scope.row.teachingDirection}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="teachingType" label="授课类型" width="100" fixed="left">
        <template #default="scope">
          <div class="button">{{scope.row.teachingType}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="teachingProgram" label="授课项目" :width="teachingProgramWidth" />
      <el-table-column prop="classHour" label="课时" width="60" />
      <el-table-column label="讲师姓名" width="100">
        <template #default="scope">
          <div style="color:#C95C19;cursor:pointer" @click="handleEdit(scope.row,1)">{{scope.row.lecturerName}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="60" />
      <el-table-column prop="position" label="职位" :width="occupationWidth" />
      <el-table-column prop="mobile" label="联系电话" width="120" />
      <el-table-column prop="lessonRemuneration" label="课酬(天)" width="100">
        <template #default="scope">
          {{proxy.$utils.formatNumber(scope.row.lessonRemuneration)}}
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
      <el-table-column prop="permanentResidence" label="常住地" width="100" fixed="right" />
      <el-table-column prop="introduce" label="讲师评价" width="130" fixed="right">
        <template #default="scope">
          <el-rate v-model="scope.row.rate" disabled />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="100">
        <template #default="scope">
          <div class="button" @click="handleEdit(scope.row,2)">编辑</div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :selectNum="selectData.length" v-if="tableData['total']" :total="tableData['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-drawer size="650px" v-model="drawer" title="新增/编辑" direction="rtl" :before-close="handleClose">
      <el-form :model="model" label-width="110px" ref="ruleFormRef" :rules="rules">
        <div class="bold title">授课信息</div>
        <el-form-item label="授课方向" prop="teachingDirection">
          <div v-if="isSeeView">{{model.teachingDirection}}</div>
          <el-select v-else v-model="model.teachingDirection" default-first-option placeholder="请选择" clearable filterable allow-create>
            <el-option v-for="(item,index) in teachingDirectionOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课类型" prop="teachingType">
          <div v-if="isSeeView">{{model.teachingType}}</div>
          <el-select v-else v-model="model.teachingType" placeholder="请选择" default-first-option clearable filterable allow-create>
            <el-option v-for="(item,index) in teachingTypeOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课项目" prop="teachingProgram">
          <div v-if="isSeeView">{{model.teachingProgram}}</div>
          <el-select v-else v-model="model.teachingProgram" placeholder="请选择" default-first-option clearable filterable allow-create>
            <el-option v-for="(item,index) in teachingProgramOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="课时">
          <div v-if="isSeeView">{{model.classHour}}</div>
          <el-input v-else v-model="model.classHour" placeholder="课时" clearable />
        </el-form-item>

        <div class="bold title">讲师信息</div>
        <el-form-item label="讲师姓名" prop="lecturerName">
          <div v-if="isSeeView">{{model.lecturerName}}</div>
          <el-input v-else v-model="model.lecturerName" placeholder="讲师姓名" clearable />
        </el-form-item>
        <el-form-item label="证书编号">
          <div v-if="isSeeView">{{model.academicCertificateNumber}}</div>
          <el-input v-else v-model="model.academicCertificateNumber" placeholder="证书编号" clearable />
        </el-form-item>
        <el-form-item label="身份证号">
          <div v-if="isSeeView">{{model.idCard}}</div>
          <el-input v-else v-model="model.idCard" placeholder="证书编号" clearable />
        </el-form-item>
        <el-form-item label="讲师性别">
          <div v-if="isSeeView">{{model.sex}}</div>
          <el-radio-group v-model="model.sex" v-else>
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话">
          <div v-if="isSeeView">{{model.mobile}}</div>
          <el-input v-model="model.mobile" placeholder="联系电话" clearable v-else />
        </el-form-item>
        <el-form-item label="职位">
          <div v-if="isSeeView">{{model.position}}</div>
          <el-input v-model="model.position" placeholder="职位" clearable v-else />
        </el-form-item>
        <el-form-item label="课酬(天)">
          <div v-if="isSeeView">{{model.lessonRemuneration}}</div>
          <el-input v-model="model.lessonRemuneration" v-else placeholder="课酬（天）" type="number" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <div v-if="isSeeView">{{model.remarks}}</div>
          <el-input v-model="model.remarks" placeholder="备注" clearable v-else />
        </el-form-item>
        <el-form-item label="常住地">
          <div v-if="isSeeView">{{model.permanentResidence}}</div>
          <el-select v-else v-model="model.permanentResidence" placeholder="请选择" clearable filterable allow-create default-first-option>
            <el-option v-for="(item,index) in permanentResidenceOptions" :key="index" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="讲师评价">
          <el-rate v-model="model.rate" allow-half :disabled="isSeeView" size="large" />
        </el-form-item>
        <el-form-item label="讲师简介">
          <div v-if="isSeeView">{{model.introduce}}</div>
          <el-input v-else v-model="model.introduce" placeholder="讲师简介" clearable type="textarea" :autosize="{ minRows:  4 }" />
        </el-form-item>
        <el-form-item label="讲师材料">
          <div style="width:100%">
            <el-button type="primary" v-if="!model.file.length" text @click="proxy.$refs.FileUploaderRef.inputClick()">上传附件</el-button>
            <div v-for="(el,idx) in model.file" :key="idx" class="flex alignCenter justifyBetween">
              <el-link :href="el.path" target="_blank">{{el.name}}</el-link>
              <el-button type="danger" text @click="model.file=[]" v-if="!isSeeView">删除</el-button>
            </div>
            <FileUploader showPop="0" :limit="1" dataType="jsonArr" v-model="model.file" ref="FileUploaderRef"></FileUploader>
          </div>
        </el-form-item>
        <div v-if="isSeeView" class="fz14" style="width:100%">
          <div class="fomrLabel">授课历史</div>
          <el-row :gutter="20" v-for="(el,idx) in model.teachingHistory" :key="idx">
            <el-col :span="2">{{idx+1}}</el-col>
            <el-col :span="8">{{el.startTime}} ~ {{el.endTime}}</el-col>
            <el-col :span="14">{{el.className}}</el-col>
          </el-row>
        </div>
        <el-form-item label="授课历史" label-position="top" v-else>
          <el-table :data="model.teachingHistory" size="small">
            <el-table-column prop="date" label="日期">
              <template #default="scope">
                <datePickerRange v-model:start="scope.row.startTime" v-model:end="scope.row.endTime">
                </datePickerRange>
              </template>
            </el-table-column>
            <el-table-column width="200" label="班级">
              <template #default="scope">
                <el-input v-model="scope.row.className" placeholder="班级" clearable />
              </template>
            </el-table-column>
            <el-table-column width="50" label="操作" align="center">
              <template #header>
                <el-button type="primary" icon="plus" circle size="small" @click="teachingHistoryAdd" />
              </template>
              <template #default="scope">
                <el-button type="danger" icon="Delete" circle size="small" @click="model.teachingHistory.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确 认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();

let drawer = ref(false);
let isSeeView = ref(false);
let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  teachingDirection: "",
  teachingType: "",
  teachingProgram: "",
  classHour: "",
  lecturerName: "",
  lessonRemuneration: "",
  permanentResidence: "",
});
let teachingProgramWidth = ref(100); //授课项目的宽度
let model = ref({
  teachingDirection: "", //授课方向
  teachingType: "", //授课类型
  teachingProgram: "", //授课项目
  classHour: "", //课时
  lecturerName: "", //讲师姓名
  academicCertificateNumber: "", //学历证书编号
  sex: "男", //性别
  position: "", //职位
  mobile: "", //联系电话
  lessonRemuneration: "", //课时费
  remarks: "", //备注
  idCard: "", //身份证号
  teacherQualificationCertificateNumber: "", //教师资格证号
  contractStartTime: "", //合同开始期限
  contractEndTime: "", //合同结束期限
  permanentResidence: "", //常驻地
  introduce: "", //讲师简介
  teachingHistory: [], //授课历史
  file: [], //附件
  rate: 0, //评分
});
let teachingDirectionOptions = ref([]);
let teachingTypeOptions = ref([]);
let teachingProgramOptions = ref([]);
let permanentResidenceOptions = ref([]);
let rules = ref({
  teachingDirection: [
    { required: true, message: "请输入授课方向", trigger: "blur" },
  ],
  teachingType: [
    { required: true, message: "请输入授课类型", trigger: "blur" },
  ],
  teachingProgram: [
    { required: true, message: "请输入授课项目", trigger: "blur" },
  ],
  lecturerName: [
    { required: true, message: "请输入讲师姓名", trigger: "blur" },
  ],
});
let loading = ref(false);
let tableData = ref({});
let selectData = ref([]); //选中的数据
let occupationWidth = ref(150); //职业宽度
let searchHeight = ref(0);

let tableHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 55 - searchHeight.value;
  return `${hei}px`;
});

onMounted(async () => {
  await getLongest();
  await getOccupation();
  onSubmit();
  getOptions();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
});

function importTemplate() {
  proxy.$refs.inputFile.click();
  handleExport(1);
}

async function handleExport(num) {
  try {
    loading.value = true;
    switch (num) {
      case 1: //下载模板
        counter.downLoadTemplate("teacher", "师资管理导入模板");
        break;
      case 2: //下载模板
        break;
      default:
        break;
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function handleFileUpload(event) {
  try {
    loading.value = true;
    const files = event.target.files;
    //updateExcelTemplate(files);
    let file = files[0];
    let resp = await proxy.$utils.fileToJson(file);
    let list = [];
    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      if (index) {
        let obj = {
          teachingDirection: element[0], //授课方向
          teachingType: element[1], //授课类型
          teachingProgram: element[2], //授课项目
          classHour: element[3], //课时
          lecturerName: element[4], //讲师姓名
          sex: element[5], //性别
          position: element[6], //职位
          mobile: element[7], //联系电话
          lessonRemuneration: element[8], //课时费
          remarks: element[9], //备注
          permanentResidence: element[10], //常驻地
          introduce: element[11], //讲师简介
        };
        list.push(obj);
      }
    }
    await proxy.$apis.teachers({
      type: "importExcel",
      data: list,
    });
    proxy.$utils.showToast("导入成功");

    async function updateExcelTemplate(files) {
      let file = {
        name: "",
        path: "",
        type: "teacher",
      };
      file.name = files[0].name;
      file.path = await counter.uploadFile(files[0]);
      await proxy.$apis.fileTemplate({
        data: file,
        type: "update",
      });
    }
  } catch (error) {
  } finally {
    getInfo();
    getOptions();
    loading.value = false;
  }
}

function handleSelectionChange(e) {
  selectData.value = e;
}

function onSubmit() {
  formInline.value.pageIndex = 1;
  getInfo();
}

//导出
async function exportExcel() {
  try {
    let list = [];
    if (selectData.value.length) {
      list = [...selectData.value];
    } else {
      list = await proxy.$apis.teachers({ type: "query" });
    }
    let cols = []; //设置表头样式
    let arr = []; //设置数据
    list.forEach((element) => {
      cols.push({ wch: 20 });
      arr.push({
        授课方向: element.teachingDirection,
        授课类型: element.teachingType,
        授课项目: element.teachingProgram,
        课时: element.classHour,
        讲师姓名: element.lecturerName,
        性别: element.sex,
        职位: element.position,
        联系电话: element.mobile,
        课时费: element.lessonRemuneration,
        备注: element.remarks,
        常驻地: element.permanentResidence,
        讲师简介: element.introduce,
      });
    });
    let query = {
      jsonData: arr,
      cols,
    };
    await proxy.$utils.exportToExcel(query, "师资管理导出");
  } catch (error) {}
}

async function handelDelete() {
  let resp = await proxy.$utils.confirmTips("确认删除?");
  if (!resp) return;
  for (let index = 0; index < selectData.value.length; index++) {
    const element = selectData.value[index];
    await proxy.$apis.teachers({
      type: "del",
      data: { _id: element._id },
    });
  }
  proxy.$utils.showToast("删除成功");
  getInfo();
}

function handleEdit(row, num) {
  if (num == 1) isSeeView.value = true;
  model.value = proxy.$utils.formatFunction({ ...row }, { ...model.value });
  model.value._id = row._id;
  drawer.value = true;
}

function init() {
  formInline.value = {
    pageIndex: 1,
    pageSize: 50,
    teachingDirection: "",
    teachingType: "",
    teachingProgram: "",
    classHour: "",
    lecturerName: "",
    lessonRemuneration: "",
    permanentResidence: "",
  };
  getInfo();
}

async function getInfo() {
  try {
    loading.value = true;
    tableData.value = await proxy.$apis.teachers({
      type: "list",
      data: formInline.value,
    });
    console.log("tableData", tableData.value);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!proxy.$refs.ruleFormRef) return;
  await proxy.$refs.ruleFormRef.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!", fields);
    }
  });
};

async function save() {
  try {
    loading.value = true;
    await proxy.$apis.teachers({
      type: model.value._id ? "update" : "add",
      data: model.value,
    });
    proxy.$utils.showToast("保存成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function teachingHistoryAdd() {
  model.value.teachingHistory.push({
    date: "",
    startTime: "",
    endTime: "",
    className: "",
  });
}

async function getOptions() {
  let array = [
    "teachingDirection",
    "teachingType",
    "teachingProgram",
    "permanentResidence",
    "longest",
    "occupation",
  ];
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    switch (element) {
      case "teachingDirection":
        teachingDirectionOptions.value = await proxy.$apis.teachers({
          type: "options",
          data: { key: "teachingDirection" },
        });
        break;
      case "teachingType":
        teachingTypeOptions.value = await proxy.$apis.teachers({
          type: "options",
          data: { key: "teachingType" },
        });
        break;
      case "teachingProgram":
        teachingProgramOptions.value = await proxy.$apis.teachers({
          type: "options",
          data: { key: "teachingProgram" },
        });
        break;
      case "permanentResidence":
        permanentResidenceOptions.value = await proxy.$apis.teachers({
          type: "options",
          data: { key: "permanentResidence" },
        });
        break;
      default:
        break;
    }
  }
}

async function getOccupation() {
  let res = await proxy.$apis.teachers({
    type: "occupation",
  });
  if (res.data && res.data.length) {
    occupationWidth.value = res.data[0].length * 15 + 30;
  }
}

async function getLongest() {
  let resp = await proxy.$apis.teachers({
    type: "longest",
  });
  if (resp.data && resp.data.length) {
    teachingProgramWidth.value = resp.data[0].length * 15 + 30;
  }
}

async function handleClose() {
  model.value = {
    teachingDirection: "", //授课方向
    teachingType: "", //授课类型
    teachingProgram: "", //授课项目
    classHour: "", //课时
    lecturerName: "", //讲师姓名
    academicCertificateNumber: "", //学历证书编号
    sex: "男", //性别
    position: "", //职位
    mobile: "", //联系电话
    lessonRemuneration: "", //课时费
    remarks: "", //备注
    idCard: "", //身份证号
    teacherQualificationCertificateNumber: "", //教师资格证号
    contractStartTime: "", //合同开始期限
    contractEndTime: "", //合同结束期限
    permanentResidence: "", //常驻地
    introduce: "", //讲师简介
    teachingHistory: [], //授课历史
    file: [],
    rate: 0, //评分
  };
  if (proxy.$refs.ruleFormRef) proxy.$refs.ruleFormRef.resetFields();
  await getOptions();
  getInfo();
  isSeeView.value = false; //是否是预览
  drawer.value = false;
}

watch(
  () => [
    formInline.value.teachingDirection,
    formInline.value.teachingType,
    formInline.value.teachingProgram,
    formInline.value.permanentResidence,
    formInline.value.lecturerName,
    formInline.value.mobile,
    formInline.value.classHour,
    formInline.value.lessonRemuneration,
  ],
  (newValue, oldValue) => {
    if (newValue) onSubmit();
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.fomrLabel {
  color: #606266;
  width: 110px;
  text-align: right;
  margin-bottom: 18px;
}
.container {
  padding: 15px;
  .title {
    margin-bottom: 15px;
  }
  .actionBtn {
    margin-bottom: 15px;
  }
}
.el-rate {
  height: auto;
}
</style>
